import React, { useEffect, useRef, useState } from 'react';
import { Input, Radio, ConfigProvider } from 'antd';
import {
  getAppealQuery,
  getPersonalCenterAppealQuery,
} from '@/services/GovernmentTrain/GovernmentTrain';
import zhCN from 'antd/lib/locale/zh_CN';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import {
  APPEAL_HANDLE_STATUS,
  APPEAL_CATEGORY,
  appealType,
  litigationCategory,
} from '@/utils/trainUtil';
import AppealDetailModal from './Components/AppealDetailModal';
import classnames from 'classnames';
import { getAppealInfoById } from '@/services/GovernmentTrain/GovernmentTrain';
import { getUserInfo } from '@/utils/storage';
import styles from './index.less';

const { Search } = Input;
interface AppealQueryProps {
  type?: string;
}
const AppealQuery: React.FC<AppealQueryProps> = (props) => {
  const { type } = props;
  const tableRef = useRef<ActionType>();
  const userInfo = getUserInfo();
  const [size, setSize] = React.useState('');
  const [category, setCategory] = React.useState('');
  const [appealNoKeywords, setAppealNoKeywords] = useState();
  const [searchCondition, setSearchCondition] = useState({});
  const [pageParams, setPageParams] = useState<any>({
    current: 1,
    pIndex: 1,
    pSize: 10,
  });
  const [modalParams, setModalParams] = useState<{ visible: boolean; type?: string }>({
    visible: false,
    type: '',
  });
  const [detailData, setDetailData] = useState([]);

  const handleAppealSearch = (value: any) => {
    setAppealNoKeywords(value);
    handleSetPageParams({
      current: 1,
      pIndex: 1,
      pSize: 10,
    });
  };

  useEffect(() => {
    if (type === 'personalCenter') {
      setSearchCondition({
        page: pageParams.pIndex,
        size: pageParams.pSize,
        appealPersonId: userInfo.userId,
        handleState: size,
        appealType: category,
        appealCode: appealNoKeywords,
        isPublic: '1',
      });
    } else {
      setSearchCondition({
        page: pageParams.pIndex,
        size: pageParams.pSize,
        handleState: size,
        appealType: category,
        appealCode: appealNoKeywords,
        isPublic: '1',
      });
    }
  }, [size, category, pageParams, appealNoKeywords]);

  const getModal = async (type: string, id: any) => {
    setModalParams({ visible: true, type });
    await getAppealInfoById({ appealId: id })
      .then((resp) => {
        setDetailData(resp?.results);
      })
      .catch((error) => {
        throw error;
      });
  };
  const indexColumns: ProColumns[] = [
    {
      title: '诉求编码',
      dataIndex: 'appealCode',
      key: 'appealCode',
      width: 80,
    },
    {
      title: '诉求部门',
      dataIndex: 'handleOrgTitle',
      key: 'handleOrgTitle',
      width: 90,
    },
    {
      title: '诉求类型',
      dataIndex: 'appealTypeTitle',
      key: 'appealTypeTitle',
      width: 90,
    },
    {
      title: '诉求类别',
      dataIndex: 'appealCategory',
      key: 'appealCategory',
      width: 90,
      render: (appealCategory: any) => {
        return <div>{APPEAL_CATEGORY[appealCategory]}</div>;
      },
    },
    {
      title: '办理状态',
      dataIndex: 'handleState',
      key: 'handleState',
      width: 90,
      render: (handleState: any) => {
        if (handleState === '02')
          return <div style={{ color: '#E00201' }}>{APPEAL_HANDLE_STATUS[handleState]}</div>;
        return <div>{APPEAL_HANDLE_STATUS[handleState]}</div>;
      },
    },
    {
      title: '受理时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
      width: 100,
    },
    {
      title: '处理时间',
      dataIndex: 'handleTime',
      key: 'handleTime',
      width: 100,
    },
  ];
  const columns: ProColumns[] = [
    {
      title: '诉求编码',
      dataIndex: 'appealCode',
      key: 'appealCode',
    },
    {
      title: '诉求部门',
      dataIndex: 'handleOrgTitle',
      key: 'handleOrgTitle',
    },
    {
      title: '诉求类型',
      dataIndex: 'appealTypeTitle',
      key: 'appealTypeTitle',
    },
    {
      title: '诉求类别',
      dataIndex: 'appealCategory',
      key: 'appealCategory',
      render: (appealCategory: any) => {
        return <div>{APPEAL_CATEGORY[appealCategory]}</div>;
      },
    },
    {
      title: '办理状态',
      dataIndex: 'handleState',
      key: 'handleState',
      render: (handleState: any) => {
        if (handleState === '02')
          return <div style={{ color: '#E00201' }}>{APPEAL_HANDLE_STATUS[handleState]}</div>;
        return <div>{APPEAL_HANDLE_STATUS[handleState]}</div>;
      },
    },
    {
      title: '受理时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
    },
    {
      title: '处理时间',
      dataIndex: 'handleTime',
      key: 'handleTime',
    },
    {
      title: '操作',
      key: 'actions',
      valueType: 'actions',
      width: 60,
      render: (text, record) => {
        console.log('record', record);
        console.log('text', text);

        return (
          <div
            className={classnames(`${styles.tableOpt}`)}
            onClick={
              record?.handleState === '03'
                ? getModal.bind('', 'detailAdd', record?.id)
                : getModal.bind('', 'detail', record?.id)
            }
          >
            {record?.handleState === '03'
              ? record?.isSatisfactionEvaluation === '1'
                ? '查看'
                : '评价'
              : '查看'}
          </div>
        );
      },
    },
  ];

  const handleSizeChange = (e: any) => {
    setSize(e.target.value);
    handleSetPageParams({
      current: 1,
      pIndex: 1,
      pSize: 10,
    });
  };
  const handleCategoryChange = (e: any) => {
    setCategory(e.target.value);
    handleSetPageParams({
      current: 1,
      pIndex: 1,
      pSize: 10,
    });
  };
  const handleSetPageParams = (params) => {
    setPageParams({
      current: params?.pIndex,
      pIndex: params?.pIndex,
      pSize: params?.pSize,
    });
  };
  return (
    <div
      className={
        type === 'index' ? styles.indexAppealQueryTableCenter : styles.AppealQueryTableCenter
      }
    >
      <div className={styles.ScreenTop}>
        <div className={styles.line}></div>
        <div className={styles.seeText}>诉求查询</div>
        <div className={styles.searchInput}>
          <Search placeholder="请输入要查询的诉求编码" onSearch={handleAppealSearch} enterButton />
        </div>
      </div>
      <div className={styles.ScreenSee}>
        <div className={styles.oneText}>
          <div className={styles.Treatment}>处理情况：</div>
          <div className={styles.condition}>
            <Radio.Group value={size} onChange={handleSizeChange}>
              {litigationCategory?.map((item) => {
                return (
                  <Radio.Button key={item.key} value={item.value}>
                    {item.title}
                  </Radio.Button>
                );
              })}
            </Radio.Group>
          </div>
        </div>
        <div className={styles.oneText}>
          <div className={styles.Treatment}>诉求类型：</div>
          <div className={styles.condition}>
            <Radio.Group value={category} onChange={handleCategoryChange}>
              <Radio.Button value="">不限</Radio.Button>
              {appealType?.map((item) => {
                return (
                  <Radio.Button key={item.key} value={item.value}>
                    {item.title}
                  </Radio.Button>
                );
              })}
            </Radio.Group>
          </div>
        </div>
      </div>
      <div className={styles.AppealQueryTable}>
        <ConfigProvider locale={zhCN}>
          <ProTable
            size="large"
            actionRef={tableRef}
            search={false}
            toolBarRender={false}
            params={searchCondition}
            columns={type === 'index' ? indexColumns : columns}
            request={async (params) => {
              if (type === 'personalCenter') {
                const resp = await getPersonalCenterAppealQuery(params);
                if (resp?.results) {
                  return {
                    data: resp.results,
                    success: true,
                    total: resp.totalCount,
                  };
                }
              } else {
                const resp = await getAppealQuery(params);
                if (resp?.results) {
                  return {
                    data: resp.results,
                    success: true,
                    total: resp.totalCount,
                  };
                }
              }
            }}
            pagination={{
              locale: zhCN,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSize: pageParams?.pSize || 10,
              current: pageParams?.pIndex || 1,
              onChange: (pIndex, pSize) => {
                handleSetPageParams({ ...pageParams, pSize, pIndex });
              },
            }}
          />
        </ConfigProvider>
      </div>
      <AppealDetailModal
        {...modalParams}
        closeModal={() => setModalParams({ visible: false })}
        data={detailData}
        onSuccess={() => {
          tableRef.current?.reload();
        }}
      />
    </div>
  );
};

export default AppealQuery;
